<template>
	<view class="container">
		<!-- 主要内容 -->
			<!-- 分类开关 -->
			<view class="switch-item" style="display: none;">
				<view class="switch-label">分类开关</view>
				<view class="switch-container">
					<view 
						class="switch" 
						:class="{ active: categoryData.enabled }"
						@click="toggleSwitch"
					>
						<view class="switch-handle"></view>
					</view>
				</view>
			</view>
			
			<!-- 父分类选择 -->
			<view class="name-item">
				<view class="name-label">父分类(可选)</view>
				<view class="name-input-container">
					<view class="picker-container" @click="showParentPicker = true">
						<text class="picker-text" :class="{ placeholder: !selectedParent }">
							{{ selectedParent ? getCategoryPath(selectedParent) : '请选择父分类' }}
						</text>
						<text class="picker-arrow">▼</text>
					</view>
				</view>
			</view>
			
			<!-- 分类名称 -->
			<view class="name-item">
				<view class="name-label">分类名称</view>
				<view class="name-input-container">
					<input 
						class="name-input"
						type="text"
						v-model="categoryData.name"
						placeholder="请输入分类名称"
					/>
				</view>
			</view>
		
		<!-- 父分类选择器弹窗 -->
		<view v-if="showParentPicker" class="picker-modal" @click.stop="showParentPicker = false">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择父分类</text>
					<text class="picker-close" @click.stop="showParentPicker = false">×</text>
				</view>
				<view class="picker-body">
					<view 
						class="picker-option" 
						:class="{ active: !selectedParent }"
						@click="selectParent(null)"
					>
						<text>顶级分类（无父分类）</text>
					</view>
					<view 
						v-for="option in categoryOptions"
						:key="option.value"
						class="picker-option"
						:class="{ active: selectedParent === option.value }"
						@click="selectParent(option.value)"
					>
						<text>{{ option.label }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<view class="delete-button" @click="deleteCategory">
				<text class="delete-text">删除</text>
			</view>
			<view class="save-button" @click="saveCategory">
				<text class="save-text">修改</text>
			</view>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			categoryData: {
				name: '',
				enabled: true,
				id: '',
				sort: 1,
				parentCode: ''
			},
			selectedParent: null, // 选中的父分类ID
			showParentPicker: false,
			categories: [], // 分类列表
			categoryOptions: [] // 选择器选项
		}
	},
	onLoad(options) {
		// 如果有传入的分类ID，先设置分类数据
		if (options.category) {
			let category = JSON.parse(options.category)
			this.categoryData.id = category.id
			this.categoryData.name = category.name
			this.categoryData.enabled = category.status == 0
			this.categoryData.parentCode = category.parentCode || '0'
			// 设置选中的父分类
			if (category.parentCode && category.parentCode !== '0') {
				this.selectedParent = category.parentCode
			} else {
				this.selectedParent = null
			}
		}
		
		// 加载分类列表（在设置完当前分类数据后）
		this.loadCategories()
	},
	methods: {
		// 加载分类列表
		loadCategories() {
			this.$u.api.productCategory.treeData().then(res => {
				if (res && Array.isArray(res) && res.length > 0) {
					this.categories = res || []
					this.buildCategoryOptions()
				} else if (res && res.list && res.list.length > 0) {
					this.categories = res.list || []
					this.buildCategoryOptions()
				} else {
					this.categories = []
					this.categoryOptions = []
				}
			}).catch(err => {
				console.error('获取分类列表失败:', err)
				this.categories = []
				this.categoryOptions = []
			})
		},
		
		// 构建分类选项（从扁平数据构建树形结构，然后扁平化显示）
		buildCategoryOptions() {
			// 将扁平数据转换为树形结构
			const tree = this.buildTree(this.categories)
			this.categoryOptions = []
			
			// 过滤掉当前分类及其子分类（避免选择自己或自己的子分类作为父分类）
			const filteredTree = this.filterCategoryTree(tree, this.categoryData.id)
			this.flattenCategories(filteredTree, 0, '')
		},
		
		// 过滤分类树，排除当前分类及其子分类
		filterCategoryTree(categories, excludeId) {
			if (!excludeId) {
				return categories
			}
			
			return categories
				.filter(category => category.id !== excludeId)
				.map(category => {
					if (category.children && category.children.length > 0) {
						return {
							...category,
							children: this.filterCategoryTree(category.children, excludeId)
						}
					}
					return category
				})
		},
		
		// 将扁平数据转换为树形结构
		buildTree(list) {
			// 如果已经是树形结构，直接返回
			if (list && list.length > 0 && list[0].children !== undefined) {
				return list
			}
			
			const map = {}
			list.forEach(item => {
				item.children = []
				map[item.id] = item
			})
			
			const tree = []
			list.forEach(item => {
				// 使用 parentCode 字段
				const parentCode = item.parentCode || item.parentId || item.parent_id || '0'
				
				if (parentCode === '0' || parentCode === 0 || !parentCode) {
					tree.push(item)
				} else {
					const parent = map[parentCode]
					if (parent) {
						if (!parent.children) {
							parent.children = []
						}
						parent.children.push(item)
					} else {
						tree.push(item)
					}
				}
			})
			
			return tree
		},
		
		// 递归扁平化分类树（用于显示）
		flattenCategories(categories, level, prefix) {
			categories.forEach(category => {
				const label = prefix + category.name
				this.categoryOptions.push({
					label: label,
					value: category.id,
					name: category.name
				})
				
				// 递归处理子分类
				if (category.children && category.children.length > 0) {
					this.flattenCategories(category.children, level + 1, prefix + '　')
				}
			})
		},
		
		// 获取分类路径
		getCategoryPath(categoryId) {
			// 先构建树
			const tree = this.buildTree(this.categories)
			
			const findPath = (categories, targetId, path = []) => {
				for (const category of categories) {
					if (category.id === categoryId) {
						return [...path, category.name].join(' > ')
					}
					if (category.children && category.children.length > 0) {
						const found = findPath(category.children, targetId, [...path, category.name])
						if (found) {
							return found
						}
					}
				}
				return null
			}
			
			return findPath(tree, categoryId) || ''
		},
		
		// 选择父分类
		selectParent(parentId) {
			this.selectedParent = parentId
			this.categoryData.parentCode = parentId || '0'
			this.showParentPicker = false
		},
		
		toggleSwitch() {
			// 先更新本地状态
			this.categoryData.enabled = !this.categoryData.enabled
			
			// 调用接口更新状态
			this.updateCategoryStatus()
		},
		
		// 更新分类状态
		updateCategoryStatus() {
			const params = {
				id: this.categoryData.id,
				status: this.categoryData.enabled ? '0' : '2'
			}
			
			this.$u.api.productCategory.updateStatus(params).then(res => {
				if (res && res.result === 'true') {
					uni.showToast({
						title: res.message || this.categoryData.enabled ? '已禁用' : '已启用',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: res.message || '状态更新失败',
						icon: 'none'
					})
					// 恢复原状态
					this.categoryData.enabled = !this.categoryData.enabled
				}
			}).catch(err => {
				console.error('更新分类状态失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
				// 恢复原状态
				this.categoryData.enabled = !this.categoryData.enabled
			})
		},
		deleteCategory() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个分类吗？删除后不可恢复！',
				success: (res) => {
					if (res.confirm) {
						this.confirmDelete()
					}
				}
			})
		},
		
		// 确认删除分类
		confirmDelete() {
			if (!this.categoryData || !this.categoryData.id) {
				uni.showToast({
					title: '分类信息错误',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({ title: '删除中...' })
			
			const params = {
				id: this.categoryData.id
			}
			
			this.$u.api.productCategory.delete(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result === 'true') {
					uni.showToast({
						title: res.message || '删除成功',
						icon: 'success'
					})
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.message || '删除失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('删除分类失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			})
		},
		saveCategory() {
			if (!this.categoryData.name.trim()) {
				uni.showToast({
					title: '请输入分类名称',
					icon: 'none'
				})
				return
			}
			
			if (!this.categoryData.id) {
				uni.showToast({
					title: '分类ID错误',
					icon: 'none'
				})
				return
			}
			
			uni.showLoading({ title: '保存中...' })
			
			const params = {
				id: this.categoryData.id,
				name: this.categoryData.name.trim()
			}
			
			// 添加父分类参数
			if (this.selectedParent) {
				params.parentCode = this.selectedParent
			} else {
				params.parentCode = '0'
			}
			
			this.$u.api.productCategory.save(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result === 'true') {
					uni.showToast({
						title: res.message || '保存成功',
						icon: 'success'
					})
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.message || '保存失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('保存分类失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	padding: 20px;
}

/* 分类开关 */
.switch-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px 0;
	border-bottom: 1px solid #f0f0f0;
}

.switch-label {
	font-size: 14px;
	color: #333333;
}

.switch-container {
	display: flex;
	align-items: center;
}

.switch {
	width: 50px;
	height: 30px;
	background-color: #e0e0e0;
	border-radius: 15px;
	position: relative;
	transition: background-color 0.3s ease;
}

.switch.active {
	background-color: #ff4069;
}

.switch-handle {
	width: 26px;
	height: 26px;
	background-color: #ffffff;
	border-radius: 50%;
	position: absolute;
	top: 2px;
	left: 2px;
	transition: transform 0.3s ease;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.switch.active .switch-handle {
	transform: translateX(20px);
}

/* 分类名称 */
.name-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px 0;
	border-bottom: 1px solid #f0f0f0;
}

.name-label {
	font-size: 14px;
	color: #333333;
	width: 80px;
}

.name-input-container {
	flex: 1;
	margin-left: 20px;
}

.name-input {
	width: 100%;
	height: 40px;
	padding: 0 15px;
	background-color: #f5f5f5;
	border: none;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
	box-sizing: border-box;
}

.name-input::placeholder {
	color: #999999;
}

.picker-container {
	width: 100%;
	height: 40px;
	background-color: #f5f5f5;
	border-radius: 8px;
	padding: 0 10px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
}

.picker-text {
	flex: 1;
	font-size: 14px;
	color: #333333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.picker-text.placeholder {
	color: #999999;
}

.picker-arrow {
	color: #999999;
	font-size: 12px;
	margin-left: 10px;
}

/* 选择器弹窗 */
.picker-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}

.picker-content {
	width: 100%;
	background-color: #ffffff;
	border-radius: 20px 20px 0 0;
	max-height: 70vh;
	display: flex;
	flex-direction: column;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #f5f5f5;
}

.picker-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.picker-close {
	font-size: 24px;
	color: #999999;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.picker-body {
	flex: 1;
	overflow-y: auto;
	padding: 10px 0;
}

.picker-option {
	padding: 15px 20px;
	border-bottom: 1px solid #f5f5f5;
	color: #333333;
	font-size: 14px;
}

.picker-option.active {
	color: #ff4069;
	background-color: #fff8fa;
}

.picker-option:active {
	background-color: #f5f5f5;
}

/* 操作按钮 */
.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: row;
	gap: 15px;
	padding: 20px;
	background-color: #ffffff;
	box-sizing: border-box;
	z-index: 999;
}

/* 删除按钮 */
.delete-button {
	flex: 1;
	height: 50px;
	background-color: #ff4069;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.delete-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: 500;
}

/* 修改按钮 */
.save-button {
	flex: 1;
	height: 50px;
	background-color: #ff4069;
	border-radius: 25px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.save-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: 500;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
	z-index: 1000;
}
</style>
